// 查找名片函数 - 重构版
// 1. 完全重写 searchCards 函数
function searchCards(text, fields, searchScope, folderId, globalFolderIds) {
    showLoader();

    // 构建后端请求的 URL
    var url = 'BusinessCardServlet?action=searchCards&text=' + encodeURIComponent(text) + 
              '&fields=' + encodeURIComponent(fields.join(',')) + 
              '&searchScope=' + searchScope;

    // 如果是"当前文件夹"范围，则传递文件夹 ID
    if (searchScope === 'current' && folderId) {
        url += '&folder_id=' + folderId;
    }

    // 如果是全局查找，则传递所有文件夹 ID
    if (searchScope === 'global' && globalFolderIds && globalFolderIds.length > 0) {
        url += '&folder_ids=' + encodeURIComponent(globalFolderIds.join(','));
    }

    // 发起请求
    fetch(url)
        .then(function(response) {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(function(data) {
            hideLoader();
            renderSearchResults(data, text, fields);
        })
        .catch(function(error) {
            hideLoader();
            console.error('搜索名片失败:', error);
            showMessage('搜索名片失败，请重试', 'error');
        });
}

//2. 渲染搜索结果的主函数
//1. 修复 renderSearchResults 函数中的事件绑定部分
function renderSearchResults(data, searchText, fields) {
    var resultsContainer = document.getElementById('searchResults');
    
    // 完全清空之前的内容
    resultsContainer.innerHTML = '';
    
    if (!data || data.length === 0) {
        resultsContainer.innerHTML = 
            '<div style="text-align: center; padding: 40px; color: #6c757d;">' +
                '<i class="fas fa-search" style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;"></i>' +
                '<p style="font-size: 16px; margin: 0;">未找到匹配的结果</p>' +
                '<p style="font-size: 14px; margin: 8px 0 0 0; opacity: 0.7;">请尝试使用不同的关键词或搜索范围</p>' +
            '</div>';
        return;
    }
    
    // 创建搜索结果头部
    var headerDiv = document.createElement('div');
    headerDiv.style.marginBottom = '20px';
    headerDiv.style.padding = '15px';
    headerDiv.style.backgroundColor = '#e3f2fd';
    headerDiv.style.border = '1px solid #2196f3';
    headerDiv.style.borderRadius = '8px';
    headerDiv.style.display = 'flex';
    headerDiv.style.justifyContent = 'space-between';
    headerDiv.style.alignItems = 'center';
    
    var resultInfo = document.createElement('div');
    resultInfo.innerHTML = 
        '<strong style="color: #1976d2; font-size: 16px;">' +
            '<i class="fas fa-search"></i> 找到 ' + data.length + ' 条匹配结果' +
        '</strong>';
    
    // 添加重新搜索按钮
    var newSearchBtn = document.createElement('button');
    newSearchBtn.className = 'btn btn-secondary btn-sm';
    newSearchBtn.innerHTML = '<i class="fas fa-search"></i> 重新搜索';
    newSearchBtn.onclick = function() {
        document.getElementById('searchText').value = '';
        document.getElementById('searchResults').innerHTML = '';
    };
    
    headerDiv.appendChild(resultInfo);
    headerDiv.appendChild(newSearchBtn);
    resultsContainer.appendChild(headerDiv);
    
    // 创建全选控制区域
    var selectAllContainer = document.createElement('div');
    selectAllContainer.style.marginBottom = '15px';
    selectAllContainer.style.padding = '12px';
    selectAllContainer.style.backgroundColor = '#f8f9fa';
    selectAllContainer.style.borderRadius = '6px';
    selectAllContainer.style.border = '1px solid #dee2e6';
    selectAllContainer.style.display = 'flex';
    selectAllContainer.style.alignItems = 'center';
    selectAllContainer.style.justifyContent = 'space-between';
    
    var selectAllCheckbox = document.createElement('input');
    selectAllCheckbox.type = 'checkbox';
    selectAllCheckbox.id = 'selectAllSearchResults';
    selectAllCheckbox.style.marginRight = '8px';
    selectAllCheckbox.style.transform = 'scale(1.2)';
    
    var selectAllLabel = document.createElement('label');
    selectAllLabel.setAttribute('for', 'selectAllSearchResults');
    selectAllLabel.style.fontWeight = 'bold';
    selectAllLabel.style.cursor = 'pointer';
    selectAllLabel.style.display = 'flex';
    selectAllLabel.style.alignItems = 'center';
    selectAllLabel.innerHTML = '<i class="fas fa-check-square" style="margin-right: 6px;"></i> 全选搜索结果';
    
    // 选中计数显示
    var selectedCountDiv = document.createElement('div');
    selectedCountDiv.id = 'selectedSearchCount';
    selectedCountDiv.style.fontSize = '14px';
    selectedCountDiv.style.color = '#495057';
    selectedCountDiv.style.fontWeight = 'bold';
    selectedCountDiv.innerHTML = '<i class="fas fa-info-circle"></i> 已选择: <span class="count">0</span> 项';
    
    var leftDiv = document.createElement('div');
    leftDiv.style.display = 'flex';
    leftDiv.style.alignItems = 'center';
    leftDiv.appendChild(selectAllCheckbox);
    leftDiv.appendChild(selectAllLabel);
    
    selectAllContainer.appendChild(leftDiv);
    selectAllContainer.appendChild(selectedCountDiv);
    resultsContainer.appendChild(selectAllContainer);
    
    // 创建搜索结果列表容器
    var resultsList = document.createElement('div');
    resultsList.className = 'search-results-list';
    resultsList.style.marginBottom = '20px';
    
    // 生成每个搜索结果项
    for (var i = 0; i < data.length; i++) {
        var card = data[i];
        var resultItem = createSearchResultItemFixed(card, searchText, fields);
        resultsList.appendChild(resultItem);
    }
    
    resultsContainer.appendChild(resultsList);
    
    // 创建操作按钮区域
    var actionsDiv = createSearchActionsArea(data);
    resultsContainer.appendChild(actionsDiv);
    
    // 🔧 重要修复：延迟绑定全选事件，确保所有复选框都已创建
    setTimeout(function() {
        // 绑定全选事件
        selectAllCheckbox.addEventListener('change', function() {
            console.log('全选状态改变:', this.checked);
            var checkboxes = document.querySelectorAll('.search-result-checkbox');
            console.log('找到复选框数量:', checkboxes.length);
            
            for (var i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = this.checked;
                console.log('设置复选框', i, '状态为:', this.checked);
            }
            updateSearchButtonStatesFixed();
        });
        
        // 初始化按钮状态
        updateSearchButtonStatesFixed();
        console.log('搜索结果渲染完成，总共', data.length, '项');
    }, 100);
}

//2. 修复创建单个搜索结果项的函数
function createSearchResultItemFixed(card, searchText, fields) {
    var resultItem = document.createElement('div');
    resultItem.className = 'card-item search-result-item';
    resultItem.style.position = 'relative';
    resultItem.style.marginBottom = '12px';
    resultItem.style.padding = '15px';
    resultItem.style.border = '1px solid #e0e0e0';
    resultItem.style.borderRadius = '8px';
    resultItem.style.backgroundColor = '#ffffff';
    resultItem.style.transition = 'all 0.3s ease';
    
    // 鼠标悬停效果
    resultItem.addEventListener('mouseenter', function() {
        this.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)';
        this.style.transform = 'translateY(-2px)';
    });
    
    resultItem.addEventListener('mouseleave', function() {
        this.style.boxShadow = '0 2px 4px rgba(0,0,0,0.05)';
        this.style.transform = 'translateY(0)';
    });
    
    // 🔧 修复：创建复选框容器，确保点击区域足够大
    var checkboxContainer = document.createElement('div');
    checkboxContainer.style.position = 'absolute';
    checkboxContainer.style.top = '10px';
    checkboxContainer.style.right = '10px';
    checkboxContainer.style.width = '40px';
    checkboxContainer.style.height = '40px';
    checkboxContainer.style.display = 'flex';
    checkboxContainer.style.alignItems = 'center';
    checkboxContainer.style.justifyContent = 'center';
    checkboxContainer.style.cursor = 'pointer';
    checkboxContainer.style.borderRadius = '4px';
    checkboxContainer.style.backgroundColor = 'rgba(255, 255, 255, 0.9)';
    checkboxContainer.style.border = '1px solid #dee2e6';
    
    // 创建复选框
    var cardCheckbox = document.createElement('input');
    cardCheckbox.type = 'checkbox';
    cardCheckbox.className = 'search-result-checkbox';
    
    // 🔧 关键修复：统一字段名，尝试多种可能的字段名
    var cardId = card.cardId || card.card_id || card.id;
    cardCheckbox.dataset.cardId = cardId;
    
    // 🔧 调试：输出卡片数据以确认字段名
    console.log('🔧 创建复选框，卡片数据:', card);
    console.log('🔧 使用的卡片ID:', cardId);
    
    cardCheckbox.style.transform = 'scale(1.3)';
    cardCheckbox.style.cursor = 'pointer';
    cardCheckbox.style.accentColor = '#3a7bd5';
    
    // 🔧 重要修复：使用多种方式绑定事件，确保响应
    function handleCheckboxChange(event) {
        console.log('🔧 复选框点击 - ID:', cardCheckbox.dataset.cardId, '状态:', cardCheckbox.checked);
        
        // 阻止事件冒泡，避免影响其他元素
        if (event) {
            event.stopPropagation();
        }
        
        // 立即更新按钮状态
        updateSearchButtonStatesFixed();
        
        // 更新全选状态
        updateSelectAllState();
    }
    
    // 绑定多个事件确保响应
    cardCheckbox.addEventListener('change', handleCheckboxChange);
    cardCheckbox.addEventListener('click', function(event) {
        event.stopPropagation();
        // 延迟一点执行，确保复选框状态已更新
        setTimeout(handleCheckboxChange, 10);
    });
    
    // 🔧 修复：点击容器也能切换复选框状态
    checkboxContainer.addEventListener('click', function(event) {
        event.stopPropagation();
        console.log('🔧 点击复选框容器');
        cardCheckbox.checked = !cardCheckbox.checked;
        handleCheckboxChange();
    });
    
    checkboxContainer.appendChild(cardCheckbox);
    resultItem.appendChild(checkboxContainer);
    
    // 高亮显示搜索文本
    var highlightedData = {};
    highlightedData.name = highlightSearchText(card.name || '', searchText);
    highlightedData.organization = highlightSearchText(card.organization || '', searchText);
    highlightedData.title = highlightSearchText(card.title || '', searchText);
    highlightedData.phone = highlightSearchText(card.phone || '', searchText);
    highlightedData.email = highlightSearchText(card.email || '', searchText);
    highlightedData.address = highlightSearchText(card.address || '', searchText);
    
    // 生成名片内容HTML
    var contentHtml = 
        '<div style="margin-right: 50px;">' +
            '<h3 style="margin-bottom: 8px; color: #2c3e50; font-size: 18px;">' +
                '<i class="fas fa-user" style="margin-right: 8px; color: #3498db;"></i>' +
                highlightedData.name +
            '</h3>' +
            '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 10px;">' +
                '<p style="margin: 0;"><strong><i class="fas fa-building" style="width: 16px; margin-right: 6px; color: #9b59b6;"></i>机构:</strong> ' + highlightedData.organization + '</p>' +
                '<p style="margin: 0;"><strong><i class="fas fa-briefcase" style="width: 16px; margin-right: 6px; color: #e67e22;"></i>职务:</strong> ' + highlightedData.title + '</p>' +
                '<p style="margin: 0;"><strong><i class="fas fa-phone" style="width: 16px; margin-right: 6px; color: #27ae60;"></i>电话:</strong> ' + highlightedData.phone + '</p>' +
                '<p style="margin: 0;"><strong><i class="fas fa-envelope" style="width: 16px; margin-right: 6px; color: #3498db;"></i>邮箱:</strong> ' + highlightedData.email + '</p>' +
            '</div>' +
            '<p style="margin: 0; color: #7f8c8d; font-size: 14px;">' +
                '<i class="fas fa-map-marker-alt" style="width: 16px; margin-right: 6px; color: #e74c3c;"></i>' +
                '<strong>地址:</strong> ' + highlightedData.address +
            '</p>' +
            '<p style="margin: 8px 0 0 0; color: #95a5a6; font-size: 13px; font-style: italic;">' +
                '<i class="fas fa-folder" style="width: 16px; margin-right: 6px;"></i>' +
                '所属文件夹: ' + (card.folderName || '（未分类）') +
            '</p>' +
        '</div>';
    
    resultItem.innerHTML += contentHtml;
    
    return resultItem;
}

//5. 修复获取选中ID函数
function getSelectedSearchCardIdsFixed() {
    var selectedCardIds = [];
    var checkboxes = document.querySelectorAll('.search-result-checkbox:checked');
    
    console.log('🔧 获取选中的名片，找到复选框数量:', checkboxes.length);
    
    for (var i = 0; i < checkboxes.length; i++) {
        var checkbox = checkboxes[i];
        console.log('🔧 处理复选框', i, '的dataset:', checkbox.dataset);
        
        // 🔧 修复：尝试多种可能的dataset属性名
        var cardIdStr = checkbox.dataset.cardId || checkbox.dataset.cardid || checkbox.dataset.id;
        console.log('🔧 获取到的cardId字符串:', cardIdStr);
        
        var cardId = parseInt(cardIdStr);
        console.log('🔧 转换后的cardId数字:', cardId);
        
        if (!isNaN(cardId) && cardId > 0) {
            selectedCardIds.push(cardId);
            console.log('🔧 添加名片ID:', cardId);
        } else {
            console.warn('🔧 无效的名片ID:', cardIdStr, '原始dataset:', checkbox.dataset);
        }
    }
    
    console.log('🔧 最终选中的名片IDs:', selectedCardIds);
    return selectedCardIds;
}

// 6. 修复处理函数使用新的获取ID函数
function handleSearchPreviewPrintFixed() {
    console.log('🔧 开始处理预览打印');
    var selectedCardIds = getSelectedSearchCardIdsFixed();
    console.log('🔧 预览打印 - 获取到的IDs:', selectedCardIds);
    
    if (selectedCardIds.length === 0) {
        showMessage('请选择要预览的名片', 'error');
        return;
    }
    
    if (!checkPermissionBeforeAction('print', '打印名片')) {
        return;
    }
    
    console.log('🔧 预览打印名片IDs:', selectedCardIds);
    printCards(selectedCardIds, true);
}

function handleSearchDirectPrintFixed() {
    console.log('🔧 开始处理直接打印');
    var selectedCardIds = getSelectedSearchCardIdsFixed();
    console.log('🔧 直接打印 - 获取到的IDs:', selectedCardIds);
    
    if (selectedCardIds.length === 0) {
        showMessage('请选择要打印的名片', 'error');
        return;
    }
    
    if (!checkPermissionBeforeAction('print', '打印名片')) {
        return;
    }
    
    if (confirm('确定要直接打印选中的 ' + selectedCardIds.length + ' 张名片吗？')) {
        console.log('🔧 直接打印名片IDs:', selectedCardIds);
        printCards(selectedCardIds, false);
    }
}


function handleSearchExportFixed() {
    console.log('🔧 开始处理导出');
    var selectedCardIds = getSelectedSearchCardIdsFixed();
    console.log('🔧 导出 - 获取到的IDs:', selectedCardIds);
    
    if (selectedCardIds.length === 0) {
        showMessage('请选择要导出的名片', 'error');
        return;
    }
    
    if (!checkPermissionBeforeAction('import_export', '导出')) {
        return;
    }
    
    var exportFilename = '搜索结果_' + new Date().toISOString().slice(0, 10).replace(/-/g, '');
    document.getElementById('exportFilename').value = exportFilename;
    document.getElementById('exportFolderId').value = '';
    document.getElementById('exportCardIds').value = JSON.stringify(selectedCardIds);
    
    if (typeof updateExportScopeInfo === 'function') {
        updateExportScopeInfo();
    }
    
    console.log('🔧 导出选中名片IDs:', selectedCardIds);
    showModal('exportModal');
}

// 7. 修复操作按钮创建函数
function createSearchActionsAreaFixed(searchResults) {
    var actionsDiv = document.createElement('div');
    actionsDiv.className = 'search-actions';
    actionsDiv.style.padding = '20px';
    actionsDiv.style.backgroundColor = '#f8f9fa';
    actionsDiv.style.borderRadius = '8px';
    actionsDiv.style.border = '1px solid #dee2e6';
    actionsDiv.style.display = 'flex';
    actionsDiv.style.gap = '12px';
    actionsDiv.style.flexWrap = 'wrap';
    actionsDiv.style.alignItems = 'center';
    actionsDiv.style.justifyContent = 'center';
    
    // 预览打印按钮
    var previewPrintButton = document.createElement('button');
    previewPrintButton.className = 'btn btn-info search-preview-btn';
    previewPrintButton.innerHTML = '<i class="fas fa-eye"></i> 预览打印';
    previewPrintButton.disabled = true;
    previewPrintButton.title = '先预览再打印选中的名片';
    previewPrintButton.onclick = handleSearchPreviewPrintFixed;
    
    // 直接打印按钮
    var directPrintButton = document.createElement('button');
    directPrintButton.className = 'btn btn-primary search-direct-btn';
    directPrintButton.innerHTML = '<i class="fas fa-print"></i> 直接打印';
    directPrintButton.disabled = true;
    directPrintButton.title = '直接打印选中的名片';
    directPrintButton.onclick = handleSearchDirectPrintFixed;
    
    // 打印所有结果按钮
    var printAllButton = document.createElement('button');
    printAllButton.className = 'btn btn-secondary search-print-all-btn';
    printAllButton.innerHTML = '<i class="fas fa-print"></i> 打印全部 (' + searchResults.length + ')';
    printAllButton.title = '打印所有搜索结果';
    printAllButton.onclick = function() {
        handleSearchPrintAll(searchResults);
    };
    
    // 导出选中按钮
    var exportSelectedButton = document.createElement('button');
    exportSelectedButton.className = 'btn btn-success search-export-btn';
    exportSelectedButton.innerHTML = '<i class="fas fa-file-export"></i> 导出选中';
    exportSelectedButton.disabled = true;
    exportSelectedButton.title = '导出选中的名片';
    exportSelectedButton.onclick = handleSearchExportFixed;
    
    // 添加所有按钮到操作区域
    actionsDiv.appendChild(previewPrintButton);
    actionsDiv.appendChild(directPrintButton);
    actionsDiv.appendChild(printAllButton);
    actionsDiv.appendChild(exportSelectedButton);
    
    return actionsDiv;
}

// 🔧 6. 修复渲染搜索结果函数，使用修复后的函数
function renderSearchResults(data, searchText, fields) {
    var resultsContainer = document.getElementById('searchResults');
    
    // 完全清空之前的内容
    resultsContainer.innerHTML = '';
    
    if (!data || data.length === 0) {
        resultsContainer.innerHTML = 
            '<div style="text-align: center; padding: 40px; color: #6c757d;">' +
                '<i class="fas fa-search" style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;"></i>' +
                '<p style="font-size: 16px; margin: 0;">未找到匹配的结果</p>' +
                '<p style="font-size: 14px; margin: 8px 0 0 0; opacity: 0.7;">请尝试使用不同的关键词或搜索范围</p>' +
            '</div>';
        return;
    }
    
    // 🔧 调试：输出搜索结果数据
    console.log('🔧 渲染搜索结果，数据:', data);
    console.log('🔧 第一条数据示例:', data[0]);
    
    // 创建搜索结果头部
    var headerDiv = document.createElement('div');
    headerDiv.style.marginBottom = '20px';
    headerDiv.style.padding = '15px';
    headerDiv.style.backgroundColor = '#e3f2fd';
    headerDiv.style.border = '1px solid #2196f3';
    headerDiv.style.borderRadius = '8px';
    headerDiv.style.display = 'flex';
    headerDiv.style.justifyContent = 'space-between';
    headerDiv.style.alignItems = 'center';
    
    var resultInfo = document.createElement('div');
    resultInfo.innerHTML = 
        '<strong style="color: #1976d2; font-size: 16px;">' +
            '<i class="fas fa-search"></i> 找到 ' + data.length + ' 条匹配结果' +
        '</strong>';
    
    // 添加重新搜索按钮
    var newSearchBtn = document.createElement('button');
    newSearchBtn.className = 'btn btn-secondary btn-sm';
    newSearchBtn.innerHTML = '<i class="fas fa-search"></i> 重新搜索';
    newSearchBtn.onclick = function() {
        document.getElementById('searchText').value = '';
        document.getElementById('searchResults').innerHTML = '';
    };
    
    headerDiv.appendChild(resultInfo);
    headerDiv.appendChild(newSearchBtn);
    resultsContainer.appendChild(headerDiv);
    
    // 创建全选控制区域
    var selectAllContainer = document.createElement('div');
    selectAllContainer.style.marginBottom = '15px';
    selectAllContainer.style.padding = '12px';
    selectAllContainer.style.backgroundColor = '#f8f9fa';
    selectAllContainer.style.borderRadius = '6px';
    selectAllContainer.style.border = '1px solid #dee2e6';
    selectAllContainer.style.display = 'flex';
    selectAllContainer.style.alignItems = 'center';
    selectAllContainer.style.justifyContent = 'space-between';
    
    var selectAllCheckbox = document.createElement('input');
    selectAllCheckbox.type = 'checkbox';
    selectAllCheckbox.id = 'selectAllSearchResults';
    selectAllCheckbox.style.marginRight = '8px';
    selectAllCheckbox.style.transform = 'scale(1.2)';
    
    var selectAllLabel = document.createElement('label');
    selectAllLabel.setAttribute('for', 'selectAllSearchResults');
    selectAllLabel.style.fontWeight = 'bold';
    selectAllLabel.style.cursor = 'pointer';
    selectAllLabel.style.display = 'flex';
    selectAllLabel.style.alignItems = 'center';
    selectAllLabel.innerHTML = '<i class="fas fa-check-square" style="margin-right: 6px;"></i> 全选搜索结果';
    
    // 选中计数显示
    var selectedCountDiv = document.createElement('div');
    selectedCountDiv.id = 'selectedSearchCount';
    selectedCountDiv.style.fontSize = '14px';
    selectedCountDiv.style.color = '#495057';
    selectedCountDiv.style.fontWeight = 'bold';
    selectedCountDiv.innerHTML = '<i class="fas fa-info-circle"></i> 已选择: <span class="count">0</span> 项';
    
    var leftDiv = document.createElement('div');
    leftDiv.style.display = 'flex';
    leftDiv.style.alignItems = 'center';
    leftDiv.appendChild(selectAllCheckbox);
    leftDiv.appendChild(selectAllLabel);
    
    selectAllContainer.appendChild(leftDiv);
    selectAllContainer.appendChild(selectedCountDiv);
    resultsContainer.appendChild(selectAllContainer);
    
    // 创建搜索结果列表容器
    var resultsList = document.createElement('div');
    resultsList.className = 'search-results-list';
    resultsList.style.marginBottom = '20px';
    
    // 生成每个搜索结果项 - 🔧 使用修复后的函数
    for (var i = 0; i < data.length; i++) {
        var card = data[i];
        var resultItem = createSearchResultItemFixed(card, searchText, fields);
        resultsList.appendChild(resultItem);
    }
    
    resultsContainer.appendChild(resultsList);
    
    // 创建操作按钮区域 - 🔧 使用修复后的函数
    var actionsDiv = createSearchActionsAreaFixed(data);
    resultsContainer.appendChild(actionsDiv);
    
    // 🔧 重要修复：确保所有复选框都已创建后绑定事件
    setTimeout(function() {
        // 获取所有复选框
        var checkboxes = document.querySelectorAll('.search-result-checkbox');
        
        // 绑定全选事件
        selectAllCheckbox.addEventListener('change', function() {
            console.log('🔧 全选状态改变:', this.checked);
            
            for (var i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = this.checked;
                console.log('🔧 设置复选框', i, '状态为:', this.checked, 'ID:', checkboxes[i].dataset.cardId);
            }
            
            updateSearchButtonStatesFixed();
        });
        
        // 为每个复选框绑定变化事件
        checkboxes.forEach(function(checkbox) {
            checkbox.addEventListener('change', function() {
                updateSearchButtonStatesFixed();
            });
        });
        
        // 初始化按钮状态
        updateSearchButtonStatesFixed();
        console.log('🔧 搜索框结果渲染完成，总共', data.length, '项');
    }, 100);
}

// 更新按钮状态和选择计数
function updateSearchButtonStatesFixed() {
    var checkboxes = document.querySelectorAll('.search-result-checkbox');
    var selectAllCheckbox = document.getElementById('selectAllSearchResults');
    var selectedCountSpan = document.querySelector('#selectedSearchCount .count');
    
    var totalCheckboxes = checkboxes.length;
    var selectedCount = 0;
    
    // 计算已选中的数量
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked) {
            selectedCount++;
        }
    }
    
    // 更新已选择数目显示
    selectedCountSpan.textContent = selectedCount;
    
    // 更新全选复选框状态
    if (totalCheckboxes === 0) {
        selectAllCheckbox.checked = false;
    } else {
        selectAllCheckbox.checked = totalCheckboxes === selectedCount;
    }
    
    // 🔧 可选：根据选择状态启用/禁用操作按钮
    var actionButtons = document.querySelectorAll('#searchActions .action-btn');
    actionButtons.forEach(function(btn) {
        btn.disabled = selectedCount === 0;
        btn.style.opacity = selectedCount === 0 ? '0.5' : '1';
    });
}

// 3. 修复更新按钮状态函数
function updateSearchButtonStatesFixed() {
    var selectedCheckboxes = document.querySelectorAll('.search-result-checkbox:checked');
    var selectedCount = selectedCheckboxes.length;
    
    console.log('🔧 更新按钮状态 - 选中数量:', selectedCount);
    console.log('🔧 选中的复选框:', selectedCheckboxes);
    
    // 🔧 调试：检查每个复选框的数据
    for (var i = 0; i < selectedCheckboxes.length; i++) {
        var cb = selectedCheckboxes[i];
        console.log('🔧 复选框', i, 'dataset:', cb.dataset, 'checked:', cb.checked);
    }
    
    // 更新选中计数显示
    var countElement = document.querySelector('#selectedSearchCount .count');
    if (countElement) {
        countElement.textContent = selectedCount;
        console.log('🔧 更新计数显示为:', selectedCount);
    } else {
        console.warn('🔧 未找到计数显示元素');
    }
    
    // 获取按钮元素
    var previewBtn = document.querySelector('.search-preview-btn');
    var directBtn = document.querySelector('.search-direct-btn');
    var exportBtn = document.querySelector('.search-export-btn');
    
    console.log('🔧 找到的按钮:', {
        preview: !!previewBtn,
        direct: !!directBtn,
        export: !!exportBtn
    });
    
    // 更新按钮状态
    var hasSelection = selectedCount > 0;
    
    if (previewBtn) {
        previewBtn.disabled = !hasSelection;
        previewBtn.innerHTML = hasSelection ? 
            '<i class="fas fa-eye"></i> 预览打印 (' + selectedCount + ')' : 
            '<i class="fas fa-eye"></i> 预览打印';
        
        // 🔧 修复：更新按钮样式
        if (hasSelection) {
            previewBtn.style.opacity = '1';
            previewBtn.style.cursor = 'pointer';
        } else {
            previewBtn.style.opacity = '0.6';
            previewBtn.style.cursor = 'not-allowed';
        }
    }
    
    if (directBtn) {
        directBtn.disabled = !hasSelection;
        directBtn.innerHTML = hasSelection ? 
            '<i class="fas fa-print"></i> 直接打印 (' + selectedCount + ')' : 
            '<i class="fas fa-print"></i> 直接打印';
            
        // 🔧 修复：更新按钮样式
        if (hasSelection) {
            directBtn.style.opacity = '1';
            directBtn.style.cursor = 'pointer';
        } else {
            directBtn.style.opacity = '0.6';
            directBtn.style.cursor = 'not-allowed';
        }
    }
    
    if (exportBtn) {
        exportBtn.disabled = !hasSelection;
        exportBtn.innerHTML = hasSelection ? 
            '<i class="fas fa-file-export"></i> 导出选中 (' + selectedCount + ')' : 
            '<i class="fas fa-file-export"></i> 导出选中';
            
        // 🔧 修复：更新按钮样式
        if (hasSelection) {
            exportBtn.style.opacity = '1';
            exportBtn.style.cursor = 'pointer';
        } else {
            exportBtn.style.opacity = '0.6';
            exportBtn.style.cursor = 'not-allowed';
        }
    }
    
    console.log('🔧 按钮状态更新完成，hasSelection:', hasSelection);
}



// 创建搜索结果项的函数
//3. 创建单个搜索结果项
function createSearchResultItem(card, searchText, fields) {
    var resultItem = document.createElement('div');
    resultItem.className = 'card-item search-result-item';
    resultItem.style.position = 'relative';
    resultItem.style.marginBottom = '12px';
    resultItem.style.padding = '15px';
    resultItem.style.border = '1px solid #e0e0e0';
    resultItem.style.borderRadius = '8px';
    resultItem.style.backgroundColor = '#ffffff';
    resultItem.style.transition = 'all 0.3s ease';
    
    // 鼠标悬停效果
    resultItem.addEventListener('mouseenter', function() {
        this.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)';
        this.style.transform = 'translateY(-2px)';
    });
    
    resultItem.addEventListener('mouseleave', function() {
        this.style.boxShadow = '0 2px 4px rgba(0,0,0,0.05)';
        this.style.transform = 'translateY(0)';
    });
    
    // 创建复选框
    var cardCheckbox = document.createElement('input');
    cardCheckbox.type = 'checkbox';
    cardCheckbox.className = 'search-result-checkbox';
    cardCheckbox.dataset.cardId = card.card_id;
    cardCheckbox.style.position = 'absolute';
    cardCheckbox.style.top = '15px';
    cardCheckbox.style.right = '15px';
    cardCheckbox.style.transform = 'scale(1.3)';
    cardCheckbox.style.cursor = 'pointer';
    cardCheckbox.style.accentColor = '#3a7bd5';
    
    // 重要：绑定复选框变化事件
    cardCheckbox.addEventListener('change', function() {
        console.log('复选框状态改变:', this.checked, 'ID:', this.dataset.cardId);
        updateSearchButtonStates();
        
        // 更新全选状态
        var allCheckboxes = document.querySelectorAll('.search-result-checkbox');
        var checkedCount = document.querySelectorAll('.search-result-checkbox:checked').length;
        var selectAllCheckbox = document.getElementById('selectAllSearchResults');
        if (selectAllCheckbox) {
            selectAllCheckbox.checked = allCheckboxes.length > 0 && checkedCount === allCheckboxes.length;
        }
    });
    
    resultItem.appendChild(cardCheckbox);
    
    // 高亮显示搜索文本
    var highlightedData = {};
    highlightedData.name = highlightSearchText(card.name || '', searchText);
    highlightedData.organization = highlightSearchText(card.organization || '', searchText);
    highlightedData.title = highlightSearchText(card.title || '', searchText);
    highlightedData.phone = highlightSearchText(card.phone || '', searchText);
    highlightedData.email = highlightSearchText(card.email || '', searchText);
    highlightedData.address = highlightSearchText(card.address || '', searchText);
    
    // 生成名片内容HTML
    var contentHtml = 
        '<div style="margin-right: 50px;">' +
            '<h3 style="margin-bottom: 8px; color: #2c3e50; font-size: 18px;">' +
                '<i class="fas fa-user" style="margin-right: 8px; color: #3498db;"></i>' +
                highlightedData.name +
            '</h3>' +
            '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 10px;">' +
                '<p style="margin: 0;"><strong><i class="fas fa-building" style="width: 16px; margin-right: 6px; color: #9b59b6;"></i>机构:</strong> ' + highlightedData.organization + '</p>' +
                '<p style="margin: 0;"><strong><i class="fas fa-briefcase" style="width: 16px; margin-right: 6px; color: #e67e22;"></i>职务:</strong> ' + highlightedData.title + '</p>' +
                '<p style="margin: 0;"><strong><i class="fas fa-phone" style="width: 16px; margin-right: 6px; color: #27ae60;"></i>电话:</strong> ' + highlightedData.phone + '</p>' +
                '<p style="margin: 0;"><strong><i class="fas fa-envelope" style="width: 16px; margin-right: 6px; color: #3498db;"></i>邮箱:</strong> ' + highlightedData.email + '</p>' +
            '</div>' +
            '<p style="margin: 0; color: #7f8c8d; font-size: 14px;">' +
                '<i class="fas fa-map-marker-alt" style="width: 16px; margin-right: 6px; color: #e74c3c;"></i>' +
                '<strong>地址:</strong> ' + highlightedData.address +
            '</p>' +
            '<p style="margin: 8px 0 0 0; color: #95a5a6; font-size: 13px; font-style: italic;">' +
                '<i class="fas fa-folder" style="width: 16px; margin-right: 6px;"></i>' +
                '所属文件夹: ' + (card.folderName || '（未分类）') +
            '</p>' +
        '</div>';
    
    resultItem.innerHTML += contentHtml;
    
    return resultItem;
}

// 高亮搜索文本的安全函数 - 避免特殊字符问题
//4. 高亮搜索文本的安全函数
function highlightSearchText(text, searchText) {
    if (!text || !searchText) {
        return text || '';
    }
    
    try {
        // 简单的字符串替换，避免复杂正则表达式
        var lowerText = text.toLowerCase();
        var lowerSearch = searchText.toLowerCase();
        
        if (lowerText.indexOf(lowerSearch) !== -1) {
            // 找到匹配的位置
            var startIndex = lowerText.indexOf(lowerSearch);
            var endIndex = startIndex + searchText.length;
            
            return text.substring(0, startIndex) + 
                   '<mark style="background-color: #ffeb3b; padding: 2px 4px; border-radius: 3px; font-weight: bold;">' + 
                   text.substring(startIndex, endIndex) + 
                   '</mark>' + 
                   text.substring(endIndex);
        }
        
        return text;
    } catch (e) {
        console.warn('高亮文本失败:', e);
        return text;
    }
}

// 创建搜索操作区域
//5. 创建搜索操作区域
function createSearchActionsArea(searchResults) {
    var actionsDiv = document.createElement('div');
    actionsDiv.className = 'search-actions';
    actionsDiv.style.padding = '20px';
    actionsDiv.style.backgroundColor = '#f8f9fa';
    actionsDiv.style.borderRadius = '8px';
    actionsDiv.style.border = '1px solid #dee2e6';
    actionsDiv.style.display = 'flex';
    actionsDiv.style.gap = '12px';
    actionsDiv.style.flexWrap = 'wrap';
    actionsDiv.style.alignItems = 'center';
    actionsDiv.style.justifyContent = 'center';
    
    // 预览打印按钮
    var previewPrintButton = document.createElement('button');
    previewPrintButton.className = 'btn btn-info search-preview-btn';
    previewPrintButton.innerHTML = '<i class="fas fa-eye"></i> 预览打印';
    previewPrintButton.disabled = true;
    previewPrintButton.title = '先预览再打印选中的名片';
    
    // 直接打印按钮
    var directPrintButton = document.createElement('button');
    directPrintButton.className = 'btn btn-primary search-direct-btn';
    directPrintButton.innerHTML = '<i class="fas fa-print"></i> 直接打印';
    directPrintButton.disabled = true;
    directPrintButton.title = '直接打印选中的名片';
    
    // 打印所有结果按钮
    var printAllButton = document.createElement('button');
    printAllButton.className = 'btn btn-secondary search-print-all-btn';
    printAllButton.innerHTML = '<i class="fas fa-print"></i> 打印全部 (' + searchResults.length + ')';
    printAllButton.title = '打印所有搜索结果';
    
    // 导出选中按钮
    var exportSelectedButton = document.createElement('button');
    exportSelectedButton.className = 'btn btn-success search-export-btn';
    exportSelectedButton.innerHTML = '<i class="fas fa-file-export"></i> 导出选中';
    exportSelectedButton.disabled = true;
    exportSelectedButton.title = '导出选中的名片';
    
    // 绑定事件处理器
    previewPrintButton.onclick = function() {
        handleSearchPreviewPrint();
    };
    
    directPrintButton.onclick = function() {
        handleSearchDirectPrint();
    };
    
    printAllButton.onclick = function() {
        handleSearchPrintAll(searchResults);
    };
    
    exportSelectedButton.onclick = function() {
        handleSearchExport();
    };
    
    // 添加所有按钮到操作区域
    actionsDiv.appendChild(previewPrintButton);
    actionsDiv.appendChild(directPrintButton);
    actionsDiv.appendChild(printAllButton);
    actionsDiv.appendChild(exportSelectedButton);
    
    return actionsDiv;
}


//8. 处理预览打印
function handleSearchPreviewPrint() {
    var selectedCardIds = getSelectedSearchCardIds();
    if (selectedCardIds.length === 0) {
        showMessage('请选择要预览的名片', 'error');
        return;
    }
    
    // 检查打印权限
    if (!checkPermissionBeforeAction('print', '打印名片')) {
        return;
    }
    
    console.log('预览打印名片IDs:', selectedCardIds);
    
    // 调用预览打印功能
    printCards(selectedCardIds, true);
}

//9. 处理直接打印
function handleSearchDirectPrint() {
    var selectedCardIds = getSelectedSearchCardIds();
    if (selectedCardIds.length === 0) {
        showMessage('请选择要打印的名片', 'error');
        return;
    }
    
    // 检查打印权限
    if (!checkPermissionBeforeAction('print', '打印名片')) {
        return;
    }
    
    // 确认直接打印
    if (confirm('确定要直接打印选中的 ' + selectedCardIds.length + ' 张名片吗？')) {
        console.log('直接打印名片IDs:', selectedCardIds);
        printCards(selectedCardIds, false);
    }
}


//10. 处理打印全部
function handleSearchPrintAll(searchResults) {
    // 检查打印权限
    if (!checkPermissionBeforeAction('print', '打印名片')) {
        return;
    }
    
    var allCardIds = [];
    for (var i = 0; i < searchResults.length; i++) {
        var cardId = parseInt(searchResults[i].card_id);
        if (!isNaN(cardId)) {
            allCardIds.push(cardId);
        }
    }
    
    if (confirm('确定要打印全部 ' + allCardIds.length + ' 张名片的搜索结果吗？\n点击"确定"进行预览，点击"取消"直接打印')) {
        console.log('预览打印全部名片IDs:', allCardIds);
        printCards(allCardIds, true);
    } else {
        console.log('直接打印全部名片IDs:', allCardIds);
        printCards(allCardIds, false);
    }
}


//11. 处理导出选中
function handleSearchExport() {
    var selectedCardIds = getSelectedSearchCardIds();
    if (selectedCardIds.length === 0) {
        showMessage('请选择要导出的名片', 'error');
        return;
    }
    
    // 检查导出权限
    if (!checkPermissionBeforeAction('import_export', '导出')) {
        return;
    }
    
    // 设置导出参数并打开导出模态框
    var exportFilename = '搜索结果_' + new Date().toISOString().slice(0, 10).replace(/-/g, '');
    document.getElementById('exportFilename').value = exportFilename;
    document.getElementById('exportFolderId').value = '';
    document.getElementById('exportCardIds').value = JSON.stringify(selectedCardIds);
    
    // 更新导出范围信息
    if (typeof updateExportScopeInfo === 'function') {
        updateExportScopeInfo();
    }
    
    console.log('导出选中名片IDs:', selectedCardIds);
    showModal('exportModal');
}





//6. 更新搜索按钮状态
function updateSearchButtonStates() {
    var selectedCount = document.querySelectorAll('.search-result-checkbox:checked').length;
    console.log('更新按钮状态，选中数量:', selectedCount);
    
    // 更新选中计数显示
    var countElement = document.querySelector('#selectedSearchCount .count');
    if (countElement) {
        countElement.textContent = selectedCount;
    }
    
    // 获取按钮元素
    var previewBtn = document.querySelector('.search-preview-btn');
    var directBtn = document.querySelector('.search-direct-btn');
    var exportBtn = document.querySelector('.search-export-btn');
    
    // 更新按钮状态
    var hasSelection = selectedCount > 0;
    
    if (previewBtn) {
        previewBtn.disabled = !hasSelection;
        previewBtn.innerHTML = hasSelection ? 
            '<i class="fas fa-eye"></i> 预览打印 (' + selectedCount + ')' : 
            '<i class="fas fa-eye"></i> 预览打印';
    }
    
    if (directBtn) {
        directBtn.disabled = !hasSelection;
        directBtn.innerHTML = hasSelection ? 
            '<i class="fas fa-print"></i> 直接打印 (' + selectedCount + ')' : 
            '<i class="fas fa-print"></i> 直接打印';
    }
    
    if (exportBtn) {
        exportBtn.disabled = !hasSelection;
        exportBtn.innerHTML = hasSelection ? 
            '<i class="fas fa-file-export"></i> 导出选中 (' + selectedCount + ')' : 
            '<i class="fas fa-file-export"></i> 导出选中';
    }
}

// 更新搜索打印按钮状态
function updateSearchPrintButtonState() {
    var selectedCount = document.querySelectorAll('.search-result-checkbox:checked').length;
    
    // 更新选中计数显示
    var countElement = document.querySelector('#selectedSearchCount .count');
    if (countElement) {
        countElement.textContent = selectedCount;
    }
    
    // 获取按钮元素
    var actionsDiv = document.querySelector('.search-actions');
    if (!actionsDiv) return;
    
    var previewBtn = actionsDiv.querySelector('.btn-info');
    var directBtn = actionsDiv.querySelector('.btn-primary');
    var exportBtn = actionsDiv.querySelector('.btn-success');
    
    // 更新按钮状态
    var hasSelection = selectedCount > 0;
    if (previewBtn) previewBtn.disabled = !hasSelection;
    if (directBtn) directBtn.disabled = !hasSelection;
    if (exportBtn) exportBtn.disabled = !hasSelection;
    
    // 更新按钮文本显示选中数量
    if (hasSelection) {
        if (previewBtn) previewBtn.innerHTML = '<i class="fas fa-eye"></i> 预览打印 (' + selectedCount + ')';
        if (directBtn) directBtn.innerHTML = '<i class="fas fa-print"></i> 直接打印 (' + selectedCount + ')';
        if (exportBtn) exportBtn.innerHTML = '<i class="fas fa-file-export"></i> 导出选中 (' + selectedCount + ')';
    } else {
        if (previewBtn) previewBtn.innerHTML = '<i class="fas fa-eye"></i> 预览打印';
        if (directBtn) directBtn.innerHTML = '<i class="fas fa-print"></i> 直接打印';
        if (exportBtn) exportBtn.innerHTML = '<i class="fas fa-file-export"></i> 导出选中';
    }
}

// 获取选中的名片ID数组
//7. 获取选中的名片ID数组
function getSelectedSearchCardIds() {
    var selectedCardIds = [];
    var checkboxes = document.querySelectorAll('.search-result-checkbox:checked');
    
    for (var i = 0; i < checkboxes.length; i++) {
        var cardId = parseInt(checkboxes[i].dataset.cardId);
        if (!isNaN(cardId)) {
            selectedCardIds.push(cardId);
        }
    }
    
    console.log('获取选中的名片IDs:', selectedCardIds);
    return selectedCardIds;
}



//查找点击事件
document.getElementById('searchMenu').addEventListener('click', () => {
document.getElementById('searchText').value = '';
document.getElementById('searchResults').innerHTML = '';
showModal('searchModal');

// 初始化查找弹窗下拉框（使用现有名片夹下拉框中的选项）
setTimeout(() => {
    const folderSelect = document.getElementById('folderSelect');
    const currentRadio = document.querySelector('input[value="current"]');
    const globalRadio = document.querySelector('input[value="global"]');

    folderSelect.innerHTML = '<option value="">选择文件夹...</option>'; // 重置内容

    // 使用已有的 cardFolder 或 importFolder 下拉框作为源
    const sourceSelect = document.getElementById('cardFolder') || document.getElementById('importFolder');
    if (sourceSelect && sourceSelect.options.length > 0) {
        for (let i = 0; i < sourceSelect.options.length; i++) {
            const opt = sourceSelect.options[i];
            const clone = opt.cloneNode(true);
            folderSelect.appendChild(clone);
        }
    }

    // 设置选中逻辑
    if (currentFolder) {
        currentRadio.checked = true;
        folderSelect.disabled = false;
        folderSelect.value = currentFolder;
    } else {
        globalRadio.checked = true;
        folderSelect.disabled = true;
    }
}, 300); // 等待页面上的 select 元素加载完成
});

document.querySelectorAll('input[name="searchScope"]').forEach(radio => {
	    radio.addEventListener('change', (e) => {
	        document.getElementById('folderSelect').disabled = e.target.value !== 'current';
	    });
	});



// 开始查找按钮
document.getElementById('startSearch').addEventListener('click', () => {
const searchText = document.getElementById('searchText').value;
const searchField = document.getElementById('searchField').value;
const searchScope = document.querySelector('input[name="searchScope"]:checked').value;
const folderId = document.getElementById('folderSelect').value;

if (!searchText) {
    showMessage('请输入查找内容', 'error');
    return;
}

if (searchScope === 'current' && !folderId) {
    showMessage('请选择要搜索的文件夹', 'error');
    return;
}
let globalFolderIds = null;
if (searchScope === 'global') {
    // 从全局变量中获取所有文件夹 ID
    if (window.folders && Array.isArray(window.folders)) {
        globalFolderIds = window.folders.map(folder => folder.folderId);
    } else {
        console.error('无法获取文件夹数据，全局变量 "folders" 未定义或格式不正确');
        showMessage('没有可搜索的文件夹，请创建文件夹后再尝试全局查找', 'error');
        return;
    }
}
//发起搜索，传递相关参数
searchCards(searchText, [searchField], searchScope, folderId, globalFolderIds);
});

//全选复选框点击事件
document.getElementById('selectAll').addEventListener('change', (e) => {
const checkboxes = document.querySelectorAll('.select-card');
checkboxes.forEach(checkbox => {
    checkbox.checked = e.target.checked;
});
});

//单独复选框的变化监听，确保当所有复选框都被勾选时，全选复选框会被勾选
document.querySelectorAll('.select-card').forEach(checkbox => {
checkbox.addEventListener('change', () => {
    const checkboxes = document.querySelectorAll('.select-card');
    const allChecked = [...checkboxes].every(checkbox => checkbox.checked);
    document.getElementById('selectAll').checked = allChecked;
});
});


//------------------------------------------------------------查找新增---------------------------------------------------------------------

//------------------------------------------------------------查找新增---------------------------------------------------------------------

//执行替换
function replaceCardField(replaceText, replaceAll) {
const checkedBoxes = document.querySelectorAll('.replace-checkbox:checked');

if (checkedBoxes.length === 0) {
  showMessage('请选择要替换的项', 'error');
  return;
}

let replaceCount = 0;

if (replaceAll) {
  // 全部替换
  checkedBoxes.forEach((checkbox, index) => {
    const cardId = checkbox.dataset.cardId;
    const folderId = checkbox.dataset.folderId;
    const field = checkbox.dataset.field;
    const oldValue = checkbox.dataset.original;

    replaceSingleField(cardId, folderId, field, oldValue, replaceText, checkbox, () => {
      replaceCount++;
      if (replaceCount === checkedBoxes.length) {
        showMessage(`全部替换完成，共替换 ${replaceCount} 项`, 'success');
        updateReplaceResults();
      }
    });
  });
} else {
  // 逐个替换：只替换第一个勾选的项
  const checkbox = checkedBoxes[0];
  const cardId = checkbox.dataset.cardId;
  const folderId = checkbox.dataset.folderId;
  const field = checkbox.dataset.field;
  const oldValue = checkbox.dataset.original;

  replaceSingleField(cardId, folderId, field, oldValue, replaceText, checkbox, () => {
    showMessage(`替换成功`, 'success');
    checkbox.checked = false;

    // 滚动到下一个未替换的选项
    const nextCheckbox = document.querySelector('.replace-checkbox:checked');
    if (nextCheckbox) {
      nextCheckbox.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  });
}
}

//替换调用后端
function replaceSingleField(cardId, folderId, field, oldValue, newValue, checkboxElement, callback) {
	console.group("🚀 replaceSingleField 调试开始");
  console.log("输入参数:");
  console.log("  cardId:", cardId);
  console.log("  folderId:", folderId);
  console.log("  field:", field);
  console.log("  oldValue:", oldValue);
  console.log("  newValue:", newValue);

const payload = {
  cardId: parseInt(cardId),
  folderId: parseInt(folderId),
  field: field,
  oldValue: oldValue,
  newValue: newValue
};

fetch('BusinessCardServlet?action=replaceSingle', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(payload)
})
.then(res => res.json())
.then(result => {
	  if (result.success) {
		  const resultItem = checkboxElement.closest('.result-item');
		  const fieldParagraphs = resultItem.querySelectorAll('p');

		  fieldParagraphs.forEach(p => {
		    // 更新字段显示行
		    if (p.innerText.includes(field + ':')) {
		      p.innerHTML = `<em>${field}:</em> <span style="color: green">${newValue}</span>`;
		    }

		    // 同时更新其他字段中值（比如 organization 在标题行）
		    const regex = new RegExp(highlightText(oldValue, oldValue), 'g');
		    p.innerHTML = p.innerHTML.replace(regex, `<span style="color: green">${newValue}</span>`);
		  });

		  // 添加灰色状态
		  resultItem.classList.add('replaced');
		  checkboxElement.checked = false;
		  callback();
		}
else {
    showMessage('替换失败：' + result.message, 'error');
  }
})
.catch(err => {
  console.error('替换出错:', err);
  showMessage('替换失败，请稍后重试', 'error');
});
}

//打开替换模态框
document.getElementById('replaceMenu').addEventListener('click', () => {
document.getElementById('findText').value = '';
document.getElementById('replaceText').value = '';
document.getElementById('replaceResults').innerHTML = '';
showModal('replaceModal');
});

//为模态框的关闭按钮添加点击事件监听器
document.querySelector('#replaceModal .close').addEventListener('click', function() {
  // 获取模态框元素
  const replaceModal = document.getElementById('replaceModal');
  // 隐藏模态框
  replaceModal.style.display = 'none';

  // 如果当前正在查看某个文件夹，则刷新该文件夹的卡片列表
  if (currentFolder) {
      loadCards(currentFolder);
  }
  // 刷新名片夹列表（这将更新每个文件夹的卡片计数等信息）
  loadFolders();
});
//查找匹配项
document.getElementById('startReplaceSearch').addEventListener('click', function () {
	
const findText = document.getElementById('findText').value;
const replaceField = document.getElementById('replaceField').value;

if (!findText) {
  showMessage('请输入查找内容', 'error');
  return;
}


  
const formData = new URLSearchParams();
formData.append('search_text', findText);
formData.append('field', replaceField); 



fetch('BusinessCardServlet?action=findReplaceMatches', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    body: formData.toString()
})
.then(response => {
    if (!response.ok) {
        throw new Error('网络响应不正常');
    }
    return response.json();
})
  .then(data => {
  	
    const container = document.getElementById('replaceResults');
    container.innerHTML = '';

    if (!data || data.length === 0) {
      container.innerHTML = '<p>没有找到匹配项</p>';
      
      return;
    }

    const selectAllButton = document.createElement('button');
    selectAllButton.id = 'selectAll';
    selectAllButton.innerText = '全选';
    Object.assign(selectAllButton.style, {
      backgroundColor: '#4CAF50',
      color: 'white',
      padding: '10px 15px',
      border: 'none',
      borderRadius: '5px',
      cursor: 'pointer',
      fontSize: '16px',
      marginBottom: '20px',
      transition: 'background-color 0.3s ease'
    });
    selectAllButton.addEventListener('mouseover', () => selectAllButton.style.backgroundColor = '#45a049');
    selectAllButton.addEventListener('mouseout', () => selectAllButton.style.backgroundColor = '#4CAF50');

    container.appendChild(selectAllButton);

    data.forEach(function (item) {
      const folder = item.folderPath || '(未知文件夹)';
      const div = document.createElement('div');
      div.className = 'result-item';
      div.style.padding = '10px';
      div.style.border = '1px solid #ddd';
      div.style.borderRadius = '5px';
      div.style.marginBottom = '10px';

      const checkbox = document.createElement('input');
      checkbox.type = 'checkbox';
      checkbox.className = 'replace-checkbox';
      checkbox.setAttribute('data-card-id', item.cardId);
      checkbox.setAttribute('data-folder-id', item.folderId);
      checkbox.setAttribute('data-original', item.originalValue);
      checkbox.setAttribute('data-field', item.field);
      checkbox.style.marginRight = '10px';

      const label = document.createElement('label');
      label.innerText = '选择替换';

      div.appendChild(checkbox);
      div.appendChild(label);
      div.innerHTML +=
        '<p><strong>' + highlightText(item.name, findText) + '</strong> - ' + highlightText(item.organization, findText) + '</p>' +
        '<p><em>职务:</em> ' + highlightText(item.title, findText) + '</p>' +
        '<p><em>电话:</em> ' + highlightText(item.phone, findText) + '</p>' +
        '<p><em>邮箱:</em> ' + highlightText(item.email, findText) + '</p>' +
        '<p><em>地址:</em> ' + highlightText(item.address, findText) + '</p>' +
        '<p><em>' + item.field + ':</em> ' + highlightText(item.originalValue, findText) + '</p>' +
        '<p class="folder-path">所属文件夹：<span>' + folder + '</span></p>';

      container.appendChild(div);
    });

    selectAllButton.addEventListener('click', function () {
      document.querySelectorAll('.replace-checkbox').forEach(cb => cb.checked = true);
    });
  })
  .catch(function (error) {
    console.error('查找失败:', error);
    showMessage('查找失败，请重试', 'error');
  });
});

//高亮函数
function highlightText(text, searchText) {
const regex = new RegExp('(' + searchText + ')', 'gi');
return text.replace(regex, '<span class="highlight">$1</span>');
}

//替换按钮事件
document.getElementById('replaceOne').addEventListener('click', () => {
const replaceText = document.getElementById('replaceText').value;
replaceCardField(replaceText, false);
});

document.getElementById('replaceAll').addEventListener('click', () => {
	  const findText = document.getElementById('findText').value;
	  const replaceText = document.getElementById('replaceText').value;

	  if (!findText) {
	    showMessage('请输入查找内容', 'error');
	    return;
	  }

	  if (!replaceText) {
	    showMessage('请输入替换内容', 'error');
	    return;
	  }

	  const checkedBoxes = document.querySelectorAll('.replace-checkbox:checked');

	  if (checkedBoxes.length === 0) {
	    showMessage('请选择要替换的项', 'error');
	    return;
	  }
   console.log(findText+replaceText);
   
	  if (confirm("确定将所有选中名片中的“" + findText + "”替换为“" + replaceText + "”?")) {
	    let successCount = 0;

	    checkedBoxes.forEach((checkbox, index) => {
	      const cardId = checkbox.dataset.cardId;
	      const folderId = checkbox.dataset.folderId;
	      const field = checkbox.dataset.field;
	      const oldValue = checkbox.dataset.original;

	      replaceSingleField(cardId, folderId, field, oldValue, replaceText, checkbox, () => {
	        successCount++;

	        // ✅ 替换后更新显示样式
	        const resultItem = checkbox.closest('.result-item');
	        const fieldParagraphs = resultItem.querySelectorAll('p');

	        fieldParagraphs.forEach(p => {
	          if (p.innerText.includes(field + ':')) {
	            p.innerHTML = `<em>${field}:</em> <span style="color: green">${replaceText}</span>`;
	          }
	        });

	        checkbox.checked = false;
	        checkbox.disabled = true;
	        checkbox.nextSibling.textContent = '已替换';

	        // ✅ 所有替换完成后提示
	        if (successCount === checkedBoxes.length) {
	          showMessage("全部替换完成，共替换 "+successCount+" 项为"+replaceText, 'success');
	          console.log("数量"+successCount);
	        }
	      });
	    });
	  }
	});
